import { getSignInState, signIn, getLiveInfo } from '../../api/index/index';
import { getToken, setToken, setLiveId, getLiveId, setUseTipFlag, getUseTipFlag, getUserInfo, setUserInfo, clearStorage } from '../../utils/storage';
import { getCurrentTimestamp, dateCompare } from '../../utils/date';
import { showWxToast } from '../../utils/index';
import { API_HOST } from '../../assets/constant/host';

const app = getApp();
// 观察者模式 监听活动信息是否获取到
const Observer = {};

// 作为应付审核的liveId
const LIVEID = 'afb94fa7142f43adb3c5dc8bc61d2d9b';
const LIVEID2 = 'b747b2fa4a134d2ab1a00150f4971e60';
const DEFAULTAVATOR =
  'https://static.joymew.com/joymewScreen/defaultHeadImg2.png';
const EXAMINETOKEN =
  'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHQiOjE2OTc1MzA4ODAxNzcsInVpZCI6ImFiOWIyNDIwNDk0YzRhNGJhYWEyNzE3Mjk0Y2Y2NzM4IiwiaWF0IjoxNjk2OTI2MDgwMTc3fQ.8zEIIp_UJ12J3qccTO2zxGlGODUFz9f7hJbr96i-dGE';
Page({
  data: {
    liveId: '',
    needAuth: false, // 是否需要授权登录
    isOverdate: false,// 活动是否过期
    isValid: true,// 活动是否有效
    isExamine: false, // 是否是isExamine live
  },
  onLoad: function (options) {
    console.log('options:', options);
    let that = this;
    let tmpLiveId = '';
    let stLiveId = getLiveId();// 缓存中的liveId

    // 观察者模式 监听活动信息是否获取到
    Object.defineProperty(Observer, 'liveInfoGetted', {
      configurable: true,
      enumerable: true,
      get() {
        return false;
      },
      set(val) {
        if (val) {
          console.log('***liveInfoGetted***');
          // 活动信息获取到后 执行主逻辑
          that.mainLogic();
        }
      },
    });
    // 获取liveId                                                                                          
    if (options.q) {
      // 扫码进入
      tmpLiveId = decodeURIComponent(options.q).split('?')[1].split('=')[1];
      if (!this.validateExamineLive(tmpLiveId)) {
        this.setExamine();
        return;
      }
      if (!tmpLiveId) {
        showWxToast('微信版本过低!');
      } else {
        this.setData({
          liveId: tmpLiveId,
        });
      }
    } else if (options.liveId) {
      if (!this.validateExamineLive(options.liveId)) {
        this.setExamine();
        return;
      }
      // 分享带参进入
      tmpLiveId = options.liveId;
      this.setData({
        liveId: tmpLiveId,
      });
    } else if (stLiveId) {
      if (!this.validateExamineLive(stLiveId)) {
        this.setExamine();
        return;
      }
      // 直接进入
      this.setData({
        liveId: stLiveId,
      });
    } else {
      this.setExamine();
    }
    setLiveId(this.data.liveId);
  },

  onShow: function () {
    if (this.data.isExamine) {
      wx.redirectTo({
        url: '/pages/index/index',
      });
      return;
    }
    getLiveInfo().then((res) => {
      console.log('活动信息:', res);
      if (res && res.data && res.data.splid) {
        app.globalData.activityTitle = res.data.splid.theme;
        // 设置扭一扭奖项列表
        const tmpNynPrizeArray = [];
        const tmpNynList = res.data.nynList.split(',');
        for (let i = 0; i < tmpNynList.length; i++) {
          if (tmpNynList[i] !== '-1') {
            if (tmpNynList[i] === '0') {
              tmpNynPrizeArray.push({
                desc: '谢谢参与',
                endIndex: i,
              });
            } else {
              tmpNynPrizeArray.push({
                desc: tmpNynList[i] + '元',
                endIndex: i,
              });
            }
          }
        }
        app.globalData.nynList = tmpNynPrizeArray;
        if (dateCompare(res.data.splid.using_date)) {
          showWxToast('活动已结束!');
          this.setData({
            isOverdate: true,
          });
        } else {
          // 通知活动信息已经获取到可以执行主逻辑了
          Observer.liveInfoGetted = true;
        }
      } else {
        showWxToast('活动信息获取错误，请重新进入!');
        this.setData({
          isValid: false,
        });
      }
    });
  },
  onShareAppMessage: function () {
    return {
      title: this.data.activityTitle,
      path: '/pages/joymewIndex/joymewIndex?liveId=' + this.data.liveId,
      imageUrl: '/assets/image/shareCard.png',
    };
  },
  mainLogic() {
    console.log('***执行主逻辑***');
    if (this.data.isOverdate) {
      return;
    }
    const stToken = getToken();
    const stUserInfo = getUserInfo();
    if (!stToken || !stUserInfo.nickName || !stUserInfo.avatarUrl || (stUserInfo.avatarUrl === DEFAULTAVATOR && this.data.liveId !== LIVEID)) {
      this.setData({
        needAuth: true,
      });
      return;
    }
    // 初始化用户信息
    app.setUserInfo();
    // 判断是否签到
    getSignInState().then((res) => {
      console.log('***签到状态***');
      console.log(res);
      const isSign = res.data.qian_dao_le_me;
      if (isSign) {
        console.log('***不需要签到***');
        // 不需要签到
        this.toLive();
      }
    }).catch((err) => {
      console.log(err);
      // token过期需要授权登录
      this.setData({
        needAuth: true,
      });
    });
  },
  /**
 * 判断是否签到--->签到逻辑
 */
  sign() {
    if (this.data.isOverdate) {
      showWxToast('活动已结束!');
      return;
    }
    if (!this.data.isValid) {
      showWxToast('活动信息错误，请重新进入!');
      return;
    }
    getSignInState().then((res) => {
      console.log('***sign 获取签到状态***');
      console.log(res);
      return res.data.qian_dao_le_me;
    }).then((res2) => {
      console.log(res2);
      if (!res2) {
        // 需要签到
        return signIn();
      } else {
        // 不需要签到
        this.toLive();
      }
    }).then((res3) => {
      if (res3 && res3.success) {
        console.log('***签到接口返回***');
        console.log(res3);
        this.toLive();
      }
    }).catch((err) => {
      console.log(err);
      // token过期需要重新授权登录
      if (err === '401') {
        this.setData({
          needAuth: true,
        });
      }
    });
  },
  // 跳转live页面
  toLive() {
    console.log('***app globalData中的数据***');
    console.log(app.globalData);
    console.log('***跳转live***');
    // h5是否提示过的标识 缓存中有值说明提示过 没有值说明没有提示过
    const useTipFlag = getUseTipFlag();
    const staicUrl = `${API_HOST}?liveId=${getLiveId()}&token=${getToken()}&time=${getCurrentTimestamp()}`;
    let variableUrl = '';
    if (useTipFlag) {
      variableUrl = '';
    } else {
      variableUrl = '&useTipFlag=1';
    }
    if (variableUrl) {
      app.setH5Url(staicUrl + variableUrl);
      // 缓存中标记已经提示过
      setUseTipFlag();
      console.log(staicUrl + variableUrl);
    } else {
      app.setH5Url(staicUrl);
      console.log(staicUrl);
    }
    wx.redirectTo({
      url: '/pages/live/live',
    });
  },
  // 授权登录成功后的回调
  handleAuthSuccess() {
    // 用户名赋值
    console.log('***用户名赋值 关闭授权框***');
    this.setData({
      needAuth: false,
    });
    // 获取签到状态
    getSignInState().then((res) => {
      console.log('***handleAuthSuccess 获取签到状态***');
      console.log(res);
      if (res.data.qian_dao_le_me) {
        // 不需要签到
        this.toLive();
      }
    }).catch((err) => {
      console.log(err);
      // token过期需要重新授权登录
      if (err === '401') {
        this.setData({
          needAuth: true,
        });
      }
    });
  },
  // 授权登录失败的回调
  handleAuthFail() {
    clearStorage();
    this.setData({
      needAuth: false,
    });
  },
  validateExamineLive(pLiveId) {
    let tFlag = true;
    if (pLiveId === LIVEID || pLiveId === LIVEID2) {
      tFlag = false;
    }
    return tFlag;
  },
  setExamine() {
    setLiveId(LIVEID);
    setToken(EXAMINETOKEN);
    setUserInfo({
      nickName: '默认用户',
      avatarUrl: DEFAULTAVATOR,
    });
    this.setData({
      liveId: LIVEID,
      isExamine: true,
    })
  }
})